//
//  ParkListTableViewCell.swift
//  YueYTProject
//
//  Created by mingke on 2021/2/7.
//

import UIKit
import MapKit


class ParkListTableViewCell: UITableViewCell {

    var titleLabel : UILabel?;
    var addresslabel : UILabel?;
    var iconImage : UIImageView?;
    var entity : ParkEntity?;
    var goButton : UIButton?;
    var images : [UIImage] = [];
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier);
        //初始化标签的位置
        self.titleLabel = UILabel.init(frame: CGRect.init(x: 80, y: 10, width: 300, height: 30));
        self.titleLabel?.font = UIFont.systemFont(ofSize: 18);
        //self.titleLabel?.backgroundColor = UIColor.blue;
        
        self.addresslabel = UILabel.init(frame: CGRect.init(x: 80, y: 50, width: 300, height: 20));
        self.addresslabel?.font = UIFont.systemFont(ofSize: 16);
        //self.addresslabel?.backgroundColor = UIColor.blue;
        
        self.iconImage = UIImageView(frame: CGRect.init(x: 10, y: 10, width: 60, height: 60));
        //iconImage?.backgroundColor = UIColor.blue;
        //添加一个出发按钮，可以调起手机地图，发起导航
        self.goButton = UIButton(type: .roundedRect);
        self.goButton!.frame = CGRect.init(x: 330, y: 25, width: 80, height: 30);
        self.goButton!.backgroundColor = UIColor.cyan;
        self.goButton!.setTitle("出发", for: .normal);
        self.goButton!.setTitle("出发...", for: .highlighted);
        self.goButton!.showsTouchWhenHighlighted = false;
        
        self.contentView.addSubview(self.goButton!);
        self.contentView.addSubview(self.titleLabel!);
        self.contentView.addSubview(self.addresslabel!);
        self.contentView.addSubview(self.iconImage!);
        //goButtonHandler
        let goButtonRecognizer = UITapGestureRecognizer(target: self, action: #selector(goButtonHandler));
        self.goButton!.addGestureRecognizer(goButtonRecognizer);
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder);
    }
    
    func fillLabelContent(param : ParkEntity) {
        self.entity = param;
        self.titleLabel?.text = param.parkName;
        self.addresslabel?.text = param.parkAddress;
        let totle = (self.entity?.parkTotle)!;
        let inUse = (self.entity?.parkInUse)!;
        let p1 = (totle / 2);
        let can = totle - inUse;
        //判断图标是否初始化
        if images.count == 0 {
            let someImage = UIImage.init(named: "../icons.bundle/some@2x.png");
            let anyImg = UIImage.init(named: "../icons.bundle/any@2x.png");
            let noneImage = UIImage.init(named: "../icons.bundle/none@2x.png");
            images.append(someImage!);
            images.append(anyImg!);
            images.append(noneImage!);
        }
        if can >= p1 {
            self.iconImage?.image = images[0];
        }else if can > 0 {
            self.iconImage?.image = images[1];
        }else {
            self.iconImage?.image = images[2];
        }
    }
    
    @objc func goButtonHandler() {
        print("出发");
        //调起地图，开启导航
        touchToGaoDeMap();
    }
    
    //苹果地图的导航模块，需要输入目的地的经纬度和名称
    func touchToAppleMap() {
        let dlat : Double = (self.entity?.parkLatitude)!;
        let dlon : Double = (self.entity?.parkLongitude)!;
        let dname : String = (self.entity?.parkAddress)!;
        let loc = CLLocationCoordinate2DMake(dlat, dlon)
        let currentLocation = MKMapItem.forCurrentLocation()
        let toLocation = MKMapItem(placemark:MKPlacemark(coordinate:loc,addressDictionary:nil))
        toLocation.name = dname;
        let boo = MKMapItem.openMaps(with: [currentLocation,toLocation], launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: NSNumber(value: true)])
        print(boo)
    }
    
    //高德地图的导航模块，需要输入应用名称，目的地经纬度和目的地的名称
    func touchToGaoDeMap() {
        let appName = "YueYT";
        let dlat : Double = (self.entity?.parkLatitude)!;
        let dlon : Double = (self.entity?.parkLongitude)!;
        let dname : String = (self.entity?.parkAddress)!;
        let way = 0;
        let urlString = "iosamap://path?sourceApplication=\(appName)&dname=\(dname)&dlat=\(dlat)&dlon=\(dlon)&t=\(way)" as String
                
        if self.openMap(urlString) == false {
            print("您还没有安装高德地图")
            let urlString = "itms-apps://itunes.apple.com/app/id452186370"
            self.openURL(urlString: urlString)

        }
    }
    
    // 打开第三方地图
    private func openMap(_ urlString: String) -> Bool {

         let urlstr =   urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        guard let url = URL(string:urlstr) else {
            return false
        }
        if UIApplication.shared.canOpenURL(url) == true {
            self.openURL(urlString: urlString as String)
            return true
        } else {
            return false
        }
    }
  func openURL(urlString:String) {
        let urlstr =   urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        
        guard let url = URL(string:urlstr) else {
            return
        }
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:]) { (success) in
                print(success);
            }
        } else {
            UIApplication.shared.openURL(url )
        }
    }
    
    // 高德经纬度转为百度地图经纬度
    // 百度经纬度转为高德经纬度，减掉相应的值就可以了。
    func getBaiDuCoordinateByGaoDeCoordinate(coordinate:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        return CLLocationCoordinate2DMake(coordinate.latitude + 0.006, coordinate.longitude + 0.0065)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
